package com.zjitc.service.impl;

import com.zjitc.common.Constant;
import com.zjitc.common.Constant.Role;
import com.zjitc.common.ServerResponse;
import com.zjitc.dao.UserDao;
import com.zjitc.pojo.User;
import com.zjitc.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import redis.clients.jedis.Jedis;

/**
 * Created by lenovo on 2018/4/1.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private static Jedis jedis;

    @Autowired
    private UserDao userDao;


    @Override
    public ServerResponse<User> login(String username, String password) {
        int count = userDao.userNameCount(username);
        if (count != 1) {
            return ServerResponse.createError("user do not exist");
        }
        User user = userDao.findByUserNameAndPassword(username, password);
        if (user == null) {
            return ServerResponse.createError("password error");
        }
        user.setPassword(null);
        user.setQuestion(null);
        user.setAnswer(null);
        return ServerResponse.createSuccess(user);
    }

    @Override
    public ServerResponse register(User user) {
        ServerResponse vaildResponse = this.checkVaild(user.getUsername(), Constant.USERNAME);
        if (!vaildResponse.success()) {
            return vaildResponse;
        }
        vaildResponse = this.checkVaild(user.getEmail(), Constant.EMAIL);
        if (!vaildResponse.success()) {
            return vaildResponse;
        }
        user.setRole(Role.ROLE_Manager);
        user.setPassword(user.getPassword());
        int Count = userDao.insert(user);
        if (Count == 0) {
            return ServerResponse.createError("用户已存在");
        }
        jedis = new Jedis();
        jedis.sadd("username",user.getUsername());
        jedis.sadd("email",user.getEmail());
        return ServerResponse.createBySuccessMessage("校验成功");

    }

    @Override
    public ServerResponse checkVaild(String str, String type) {
        jedis = new Jedis();
        if (StringUtils.isNotBlank(type)) {
            if (Constant.USERNAME.equals(type)) {
                int resultCount = userDao.checkUsername(str);
                if (resultCount > 0) {
                    jedis.sadd("email",str);
                    return ServerResponse.createError("用户名已经存在");
                }
            }
            if (Constant.EMAIL.equals(type)) {
                int resultCount = userDao.checkEmail(str);
                if (resultCount > 0) {
                    jedis.sadd("email",str);
                    return ServerResponse.createError("邮箱已被注册");
                }
            }
        } else {
            return ServerResponse.createError("其他数据错误");
        }
            if(jedis.exists(type)){
          jedis.sismember(type,str);
          }else {
              //从数据库读取,存入到缓存中
            }
        return ServerResponse.createBySuccessMessage("校验成功");
}

    @Override
    public ServerResponse selectQuestions(String username) {
        ServerResponse<String> vaildResponse = this.checkVaild(username, Constant.USERNAME);
        if (vaildResponse.success()) {
            return ServerResponse.createError("用户名不存在");
        }
        String question = userDao.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(question)) {
            return ServerResponse.createSuccess(question);
        }
        return ServerResponse.createError("该用户未设置找回密码问题");
    }

    @Override
    public ServerResponse checkAnswer(String username, String question, String answer) {
        int Count = userDao.checkAnswer(username, question, answer);
        if (Count > 0) {
            String forgetToken = UUID.randomUUID().toString();
            return ServerResponse.createSuccess(forgetToken);
        }
        return ServerResponse.createError("问题答案错误");
    }

    @Override
    public ServerResponse forgetResetPassword(String username, String passwordNew, String forgetToken) {
        if(StringUtils.isBlank(forgetToken)){
            return ServerResponse.createError("参数错误，需要Token");
        }
        ServerResponse vaildResponse = this.checkVaild(username, Constant.USERNAME);
        if(vaildResponse.success()){
            return ServerResponse.createError("用户不存在");
        }
        if(StringUtils.isBlank(forgetToken)){
            return ServerResponse.createError("Token已经失效");
        }
        int resultCount = userDao.updatePasswordByUsername(username,passwordNew);
        if(resultCount >0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        else {
            return ServerResponse.createError("Token错误，请重新获取Token");
        }
    }

    @Override
    public ServerResponse resetPassword(String passwordOld, String passwordNew, User user) {
        int Count = userDao.checkPassword(passwordOld, user.getId());
        if (Count == 0){
            return ServerResponse.createError("旧密码错误");
        }
        user.setPassword(passwordNew);
        int updateCount = userDao.updateByKey(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMessage("修改密码成功");
        }
        return ServerResponse.createError("修改密码失败");
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {
        int resultCount = userDao.checkEmailByUserId(user.getEmail(), user.getId());
        if(resultCount > 0 ){
            return ServerResponse.createError("email已存在，请更换邮箱");
        }
        User update = new User();
        update.setId(user.getId());
        update.setEmail(user.getEmail());
        update.setPhone(user.getPhone());
        update.setQuestion(user.getQuestion());
        update.setAnswer(user.getAnswer());

        int Count = userDao.updateByKey(update);
        if(Count > 0){
            return ServerResponse.createSuccess("更新个人信息成功", update);
        }
        return ServerResponse.createError("用户未登录");
    }

    @Override
    public ServerResponse getInformation(Integer id) {
        User user = userDao.selectByKey(id);
        if(user == null){
            return ServerResponse.createError("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createSuccess(user);
    }
}
